import UpdateCourse, {
  UpdateCourseMethods,
} from '@/pages/Admin/ManageCourse/components/UpdateCourse';
import {
  deleteCourseUsingDelete,
  pageCoursesUsingPost,
} from '@/services/student-management-system/kechengmokuai';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Modal, Space, Table } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

const ManageCourse: React.FC = () => {
  const initSearchParam = {
    current: 1,
    pageSize: 6,
    sortField: 'createTime',
    sortOrder: 'desc',
  };

  const [queryParam, setQueryParam] = useState<API.QueryCourseDTO>({ ...initSearchParam });
  const [dataSource, setDataSource] = useState<API.CourseVO[]>([]);
  const [open, setOpen] = useState<boolean>(false);
  const [editCourse, setEditCourse] = useState<API.CourseDTO>({});
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');
  const [total, setTotal] = useState<number>(0);
  const childRef = useRef<UpdateCourseMethods>(null);

  const handleOnEdit = (record: API.CourseVO) => {
    setTitle('编辑课程');
    setEditCourse({ ...record });
    setOpen(true);
  };

  const handleOnDelete = async (record: API.CourseVO) => {
    const res = await deleteCourseUsingDelete({ id: record.id ?? -1 });
    if (res.code === 200) {
      message.success('删除成功');
      // 这里进行处理
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      await getCourseList();
    } else {
      message.error('删除失败：' + res.msg);
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '课程名称', dataIndex: 'courseName', key: 'courseName' },
    { title: '学分', dataIndex: 'credit', key: 'credit' },
    { title: '学时', dataIndex: 'hours', key: 'hours' },
    { title: '描述', dataIndex: 'description', key: 'description' },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'options',
      render: (_: any, record: any) => (
        <Space>
          <Button size="small" onClick={() => handleOnEdit(record)}>
            编辑
          </Button>
          <Button size="small" danger onClick={() => handleOnDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const getCourseList = async () => {
    const res = await pageCoursesUsingPost(queryParam);
    if (res.code === 200) {
      message.success('获取数据成功');
      setDataSource(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } else {
      message.error('获取数据失败：' + res.msg);
    }
  };

  const handleOk = async () => {
    setConfirmLoading(true);
    try {
      const success = await childRef.current?.submitForm();
      if (success) {
        setOpen(false);
        getCourseList();
      }
    } catch (error) {
      message.error('提交数据有误，请检查后再提交');
    } finally {
      setConfirmLoading(false); // 无论成功还是失败都应重置loading状态
    }
  };

  const handleCancel = () => setOpen(false);

  const handleAddCourse = () => {
    setTitle('新增课程');
    setEditCourse({});
    setOpen(true);
  };

  useEffect(() => {
    getCourseList();
  }, [queryParam]);

  return (
    <div className="ManageCourse">
      <Form layout="inline" onFinish={(values) => setQueryParam({ ...initSearchParam, ...values })}>
        <Form.Item name="courseName" label="课程名称">
          <Input placeholder="请输入课程名称" />
        </Form.Item>
        {/*TODO 是否需要按学分与学时进行搜索查询*/}

        <Form.Item>
          <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>

      <Space style={{ marginTop: 10, marginBottom: 10 }}>
        <Button type="primary" onClick={handleAddCourse}>
          新增课程
        </Button>
      </Space>

      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          total,
          current: queryParam.current,
          pageSize: queryParam.pageSize,
          onChange: (current, pageSize) => setQueryParam({ ...queryParam, current, pageSize }),
        }}
      />

      <Modal
        title={title}
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <UpdateCourse editCourse={editCourse} onCloseModal={handleCancel} ref={childRef} />
      </Modal>
    </div>
  );
};

export default ManageCourse;
